
import random
import time

from selenium.common.exceptions import ElementClickInterceptedException, TimeoutException
from selenium.webdriver.common.by import By
from commons.base import Base
from libraries.logger import log


class Trunk(Base):
    ''''''
    """Coupon Wheel"""
    coupon_wheel_ele = (By.CSS_SELECTOR, '.lucky-wheel')
    small_coupon_wheel_close_ele = (By.CSS_SELECTOR, "#wheel-indicator-container .close-container")
    """Header"""
    search_ele = (By.CSS_SELECTOR, ".search")
    shopping_cart_ele = (By.CSS_SELECTOR, ".shopping_cart")
    slide_menu_ele = (By.CSS_SELECTOR, ".slide_menu")
    """SlideBar"""
    '''User'''
    username_ele = (By.CSS_SELECTOR, '[id*="page_header_signed"]')
    arrow_down_rotate_ele = (By.CSS_SELECTOR, ".arrow-down.rotate")
    my_orders_ele = (By.XPATH, "//a[text()='My Orders']")
    showroom_ele = (By.XPATH, "//a[text()='Showroom']")
    create_a_showroom_ele = (By.XPATH, "//a[text()='Create a Showroom']")
    begin_here_ele = (By.CSS_SELECTOR, ".btn-new-showroom")
    sign_out_ele = (By.XPATH, "//a[text()='Sign Out']")
    '''menu'''
    bridesmaids_ele = (By.XPATH, "(//a[contains(text(),'BRIDESMAIDS')])[1]")
    all_bridesmaid_dresses_ele = (By.XPATH, "//a[contains(text(),'All Bridesmaid Dresses')]")

    brides_ele = (By.XPATH, "(//a[contains(text(),'BRIDES')])[2]")
    all_wedding_dresses_ele = (By.XPATH, "//a[contains(text(),'All Wedding Dresses')]")

    moms_ele = (By.XPATH, "(//a[contains(text(),'MOMS')])[1]")
    mother_of_the_brides_dresses_ele = (By.XPATH, "(//a[contains(text(),'Mother of the Bride Dresses')])[1]")

    dresses_ele = (By.XPATH, "(//a[contains(text(),'DRESSES')])[1]")
    all_dresses_ele = (By.XPATH, "(//a[contains(text(),'All Dresses')])[1]")

    accessories_ele = (By.XPATH, "(//a[contains(text(),'ACCESSORIES')])[1]")
    all_accessories_ele = (By.XPATH, "//a[contains(text(),'All Accessories')]")

    swatches_fabrics_ele = (By.XPATH, "(//a[contains(text(),'SWATCHES & FABRICS')])[1]")
    swatches_fabrics_img_ele = (By.CSS_SELECTOR, "[href='/swatches-fabric'] .menu-banner")

    at_home_try_on_ele = (By.XPATH, "(//a[contains(text(),'AT-HOME TRY ON')])[1]")
    all_at_home_try_on_dresses_ele = (By.XPATH, "//a[contains(text(),'All At-Home Try On Dresses')]")

    sale_ele = (By.XPATH, "(//a[contains(text(),'SALE')])[1]")
    all_sale_ele = (By.XPATH, "//a[contains(text(),'All Sale')]")
    all_flash_sale_ele = (By.XPATH, "//a[contains(text(),'Flash Sale')]")
    outlet_dresses_ele = (By.XPATH, "(//a[contains(text(),'85% Off All Outlet Dresses')])[1]")

    ready_to_ship_ele = (By.XPATH, "//a[contains(text(),'85% OFF ALL OUTLET DRESSES')]")
    all_ready_to_ship_ele = (By.XPATH, "//a[contains(text(),'All Ready to Ship Dresses')]")

    slide_sign_in_ele = (By.XPATH, "//span[text()='Sign In']")
    slide_sign_up_ele = (By.XPATH, "//span[text()='Sign Up']")
    track_your_order_ele = (By.CSS_SELECTOR, '[id*="page_common_track_your_order"] a')
    country_point_ele = (By.CSS_SELECTOR, '[id*="page_header_currency"]')
    US_ele = (By.CSS_SELECTOR, "#US")
    CA_ele = (By.CSS_SELECTOR, "#CA")
    US_selected_ele = (By.CSS_SELECTOR, "#US .select_lable_selected")
    CA_selected_ele = (By.CSS_SELECTOR, "#CA .select_lable_selected")
    more_ele = (By.CSS_SELECTOR, '[id*="page_header_more"]')
    """FAQ"""
    FAQ = (By.CSS_SELECTOR, ".goods-item-positon")
    """Processing"""
    processing_ele = (By.XPATH, '//*[contains(text(),"Processing...") or contains(text(),"PROCESSING")]')
    """loading"""
    loading_icon_ele = (By.CSS_SELECTOR, ".loading-icon")
    """Cancel Dialog"""
    cancel_order_dialog_ele = (By.CSS_SELECTOR, "#cancel-order-dialog")
    cancel_order_continue_ele = (By.CSS_SELECTOR, "#cancel-order-dialog .btn.continue")

    @property
    def username(self):
        """获取用户名"""
        username_res = self.execute_javascript("return $('#user_name').text();", desc="获取已登录用户名")
        log.info(f"username: {username_res}")
        return username_res

    @property
    def __current_version(self):
        """获取版本号"""
        return self.driver.get_cookie('abtest').get('value')

    def __version_switch(self, stipulate_version: list):
        """版本切换"""
        browser_version = random.choice(stipulate_version)
        self.execute_javascript(f'document.cookie="abtest={browser_version};domain=.azazie.com;'
                                'expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";',
                                desc=f"切换到{browser_version}版本")
        self.driver.refresh()
        log.info(f"刷新浏览器，当前版本号abtest：{self.__current_version}")

    def assign_browser_version_A(self):
        """指定浏览器为A版本"""
        stipulate_version = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
        if self.__current_version not in stipulate_version:
            self.__version_switch(stipulate_version)
        return self

    def assign_browser_version_B(self):
        """指定浏览器为H版本"""
        stipulate_version = ['I', 'J', 'K', 'L', 'M', 'N', 'O', 'P']
        if self.__current_version not in stipulate_version:
            self.__version_switch(stipulate_version)
        return self

    def __wheel_handler(self):
        """大转盘处理"""
        self.wait_element_to_be_visible(self.coupon_wheel_ele, desc="等待大转盘出现", timeout=30)
        self.execute_javascript(
            "$('.lucky-wheel .close-img').click();", desc='关闭大转盘')
        time.sleep(2)

    def close_coupon_wheel(self, is_activity=False):
        """关闭小转盘"""
        if is_activity:
            self.execute_javascript("document.getElementById('index_float_banner').remove();", desc="移除活动圆盘")
        else:
            self.__wheel_handler()
            self.click_button(self.small_coupon_wheel_close_ele, desc="关闭小转盘", timeout=60)
        return self

    def unfold_slide_menu(self):
        """展开侧边栏菜单"""
        self.click_button(self.slide_menu_ele, desc="点击侧边栏按钮展开侧边栏菜单")
        return self

    def switch_country_CA(self):
        """切换国家为CA"""
        self.click_button(self.country_point_ele, desc="点击国家切换按钮，显示下拉菜单")
        self.scroll_to_down(1000)
        self.click_button(self.CA_ele, desc="点击CA按钮")
        self.wait_element_to_be_exist(self.CA_selected_ele, desc='等待CA已选元素存在', timeout=60)
        return self.driver.current_url

    def switch_country_US(self):
        """切换国家为US"""
        self.click_button(self.country_point_ele, desc="点击国家切换按钮，显示下拉菜单")
        self.scroll_to_down(1000)
        self.click_button(self.US_ele, desc="点击US按钮")
        self.wait_element_to_be_exist(self.US_selected_ele, desc='等待US已选元素存在', timeout=60)
        return self.driver.current_url

    def __remove_FAQ(self):
        """删除列表页的FQA"""
        self.execute_javascript('$("[data-datalayer-category=\'Banner\']").parents(".goods_item").remove();',
                                desc="移除FAQ")
        return self

    def __remove_be_back_soon(self):
        """移除BE BACK SOON商品"""
        self.execute_javascript("$('.sticker-type-soldOut').parents('.goods_item').remove();",
                                desc="移除BE BACK SOON商品")

    def remove_launcher(self):
        """移除右下角launcher按钮（防遮挡）"""
        self.execute_javascript(
            "document.getElementsByClassName('solvvy-v5-widget mobile position-bottom-right launcher')[0].remove();",
            desc="移除右下角Launcher")
        time.sleep(1)

    def shopping_cart(self):
        """点击右上角购物车按钮进入购物车页面"""
        time.sleep(3)
        self.click_button(self.shopping_cart_ele, desc="点击右上角购物车按钮进入购物车页面")
        return self

    def search(self):
        """点击右上角搜索按钮进入搜索页面"""
        self.click_button(self.search_ele, desc="点击右上角搜索按钮进入搜索页面")
        return self

    def click_bd_entrance(self):
        """点击BD入口"""
        self.click_button(self.bridesmaids_ele, desc="点击bridesmaids")
        time.sleep(1)
        return self

    def visit_bridesmaids_list_page(self):
        """进入bridesmaids列表页"""
        self.click_bd_entrance()
        self.click_button(self.all_bridesmaid_dresses_ele, desc="点击All Bridesmaid Dresses进入列表页")
        return self

    def click_wd_entrance(self):
        """点击WD入口"""
        self.click_button(self.brides_ele, desc="点击brides")
        time.sleep(1)
        return self

    def visit_brides_list_page(self):
        """进入brides列表页"""
        self.click_wd_entrance()
        self.click_button(self.all_wedding_dresses_ele, desc="点击All Wedding Dresses进入列表页")
        self.__remove_FAQ()
        return self

    def click_mob_entrance(self):
        """点击MOB入口"""
        self.click_button(self.moms_ele, desc="点击moms")
        time.sleep(1)
        return self

    def visit_moms_list_page(self):
        """进入moms列表页"""
        self.click_mob_entrance()
        self.click_button(self.mother_of_the_brides_dresses_ele, desc="点击Mother of the Bride Dresses进入列表页")
        self.__remove_FAQ()
        return self

    def click_sod_entrance(self):
        """点击SOD入口"""
        self.click_button(self.dresses_ele, desc="点击dresses")
        time.sleep(1)
        return self

    def visit_dresses_list_page(self):
        """进入dresses列表页"""
        self.click_sod_entrance()
        self.click_button(self.all_dresses_ele, desc="点击All Dresses进入列表页")
        return self

    def click_acc_entrance(self):
        """点击ACC入口"""
        self.click_button(self.accessories_ele, desc="点击accessories")
        time.sleep(1)
        return self

    def visit_accessories_list_page(self):
        """进入accessories列表页"""
        self.click_acc_entrance()
        self.click_button(self.all_accessories_ele, desc="点击All Accessories进入列表页")
        return self

    def remove_swatch_booklet_and_tape_measure(self):
        """移除列表页色卡书和卷尺"""
        self.execute_javascript("$('[alt*=Booklet]').parents('.goods_item').remove();"
                                "$(\"[alt*='Tape Measure']\").parents('.goods_item').remove();",
                                desc="移除列表页色卡书和卷尺")
        return self

    def click_sf_entrance(self):
        """点击SF入口"""
        self.click_button(self.swatches_fabrics_ele, desc="点击Swatches & Fabrics")
        time.sleep(1)
        return self

    def visit_swatches_fabrics_list_page(self):
        """进入swatches_fabrics列表页"""
        self.click_sf_entrance()
        self.click_button(self.swatches_fabrics_img_ele, desc="点击PLAN YOUR PERFECT WEDDING LOOK图片进入列表页")
        return self

    def click_sample_entrance(self):
        """点击sample入口"""
        self.click_button(self.at_home_try_on_ele, desc="点击At-Home Try on")
        time.sleep(1)
        return self

    def visit_at_home_try_on_list_page(self):
        """进入at_home_try_on列表页"""
        self.click_sample_entrance()
        self.click_button(self.all_at_home_try_on_dresses_ele, desc="点击All At-Home Try On Dresses进入列表页")
        self.__remove_FAQ()
        self.__remove_be_back_soon()
        return self

    def click_sale_entrance(self):
        """点击Sale入口"""
        self.click_button(self.sale_ele, desc="点击Sale")
        time.sleep(1)
        return self

    def visit_sale_list_page(self):
        """进入all sale列表页"""
        self.click_sale_entrance()
        self.click_button(self.all_sale_ele, desc="点击All Sale进入列表页")
        return self

    def visit_flash_sale_list_page(self):
        """进入flash sale列表页"""
        self.click_sale_entrance()
        self.click_button(self.all_flash_sale_ele, desc="点击Flash Sale进入列表页")
        return self

    def visit_outlet_dresses_list_page(self):
        """进入flash sale列表页"""
        self.click_sale_entrance()
        self.click_button(self.outlet_dresses_ele, desc="点击85% Off All Outlet Dresses进入列表页")
        return self

    def click_clearance_entrance(self):
        """点击clearance入口"""
        self.click_button(self.ready_to_ship_ele, desc="点击70% off all ready to ship dresses")
        time.sleep(1)
        return self

    def visit_ready_to_ship_list_page(self):
        """进入ready_to_ship列表页"""
        self.click_clearance_entrance()
        self.click_button(self.all_ready_to_ship_ele, desc="点击All Ready to Ship Dresses进入列表页")
        self.__remove_be_back_soon()
        return self

    def more(self):
        """点击More"""
        self.scroll_to_down(3000)
        self.click_button(self.more_ele, desc="点击More")
        time.sleep(1)
        return self

    def sign_in(self):
        """点击Sign In按钮"""
        self.scroll_to_down(3000)
        self.click_button(self.slide_sign_in_ele, desc="点击Sign In按钮")
        return self

    def sign_up(self):
        """点击Sign In按钮"""
        self.scroll_to_down(3000)
        self.click_button(self.slide_sign_up_ele, desc="点击Sign Up按钮")
        return self

    def track_your_order(self):
        """点击Track Your Order按钮"""
        self.click_button(self.track_your_order_ele, desc="点击Track Your Order按钮")
        return self

    def __unfold_user_oper(self):
        """点击用户名，等待用户操作展开"""
        self.click_button(self.username_ele, desc="点击用户名")
        self.wait_element_to_be_visible(self.arrow_down_rotate_ele, desc="等待用户操作展开")
        return self

    def into_order_list(self):
        """进入My Orders页面"""
        self.__unfold_user_oper()
        self.click_button(self.my_orders_ele, desc="点击My Orders进入订单列表页")
        return self

    def into_showroom(self):
        """进入showroom页面"""
        self.__unfold_user_oper()
        self.click_button(self.showroom_ele, desc="点击Showroom进入showroom页面")
        time.sleep(1)
        return self

    def create_a_showroom(self):
        """创建showroom并进入showroom页面"""
        self.__unfold_user_oper()
        self.click_button(self.create_a_showroom_ele, desc="点击Create a Showroom")
        self.click_button(self.begin_here_ele, desc="点击 BEGIN HERE")
        return self

    def sign_out(self):
        """用户登出"""
        self.__unfold_user_oper()
        self.click_button(self.sign_out_ele, desc="点击Sign Out")
        return self

    def remove_all_free_pannier_goods(self):
        """移除FREE Pannier商品"""
        self.execute_javascript("$('.sticker-type-freePannier').parents('.goods_item').remove();",
                                desc="移除FREE Pannier商品")
        return self

    def wait_processing_disappear(self):
        """等待Processing消失"""
        self.wait_element_not_to_be_visible(self.processing_ele, desc="等待Processing消失")
        return self

    def wait_loading_icon_disappear(self):
        """等待loading icon消失"""
        self.wait_element_not_to_be_visible(self.loading_icon_ele, desc="等待loading icon消失")
        return self

    def scroll_to_down(self, dis=1000):
        """向下滚动屏幕1000"""
        self.execute_javascript(f"window.scrollTo(0,{dis});", desc=f"向下滚动屏幕{dis}的距离")
        return self

    def go_to_track_your_order(self, base_url):
        """跳转到TRACK YOUR ORDER页"""
        url = f'{base_url}/user/login?has_track=1'.replace('//user/login?has_track=1', '/user/login?has_track=1')
        self.go_to(url)
        return self

    def remove_nav_bar(self):
        """移除顶部导航悬浮栏"""
        self.execute_javascript("document.getElementById('nav_bar').remove();", desc="移除顶部导航悬浮栏")
        return self

    def visit_non_batch_list_page(self):
        """随机进入非批量商品列表页（BD/WD/MOD）"""
        scenes = random.choice(['BD', 'WD', 'MOD'])
        log.info(f"随机到的列表页：{scenes}")
        if scenes == 'BD':
            self.visit_bridesmaids_list_page()
        elif scenes == 'WD':
            self.visit_brides_list_page()
            self.remove_all_free_pannier_goods()
        else:
            self.visit_moms_list_page()
        return self

    def go_to_face_masks_page(self, base_url):
        """跳转到face masks列表页"""
        url = f'{base_url}/all/face-masks'.replace('//all/face-masks', '/all/face-masks')
        self.go_to(url)
        return self

    def go_to_garment_bags(self, base_url):
        """跳转到Garment Bags列表页"""
        url = f'{base_url}/all/garment-bags'.replace('//all/garment-bags', '/all/garment-bags')
        self.go_to(url)
        return self

    def confirm_cancel_order(self):
        """确认取消订单"""
        self.wait_element_to_be_visible(self.cancel_order_dialog_ele, desc="等待Dialog出现")
        self.click_button(self.cancel_order_continue_ele, desc="点击CONTINUE")
        self.wait_processing_disappear()
        return self

    def go_to_garment_bag_booklet_tape_detail_page(self, base_url):
        """随机访问防尘袋、色卡书和皮尺的详情页"""
        goods_router_li = ['products/azazie-wedding-garment-bag?color=white',
                           'products/stretch-mesh-swatch-booklet?color=white',
                           'products/stretch-crepe-swatch-booklet',
                           'products/azazie-tape-measure']
        goods_router = random.choice(goods_router_li)
        url = f'{base_url}/{goods_router}'.replace(f'//{goods_router}', f'/{goods_router}')
        self.go_to(url)
        time.sleep(2)
        return self

    def go_to_error_sod_list_page_price_filter(self, base_url):
        """进去SOD错误的价格筛选结果列表页面"""
        url = f'{base_url}/all/dresses/with/price/priceA-B'.replace(f'//all/dresses/with/price/priceA-B',
                                                                    f'/all/dresses/with/price/priceA-B')
        self.go_to(url)
        time.sleep(2)
        return self
